package com.yboot.starter.mybatis.core.utils;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yboot.starter.common.core.constant.PageConstant;
import com.yboot.starter.common.core.web.page.PageVO;
import com.yboot.starter.mybatis.core.base.query.PageQuery;

import java.util.List;
import java.util.function.Supplier;

/**
 * @author yangcs
 */
public class MybatisPageUtil {

    public static <T> Page<T> initPage(PageQuery pageQuery) {
        int pageNumber = getPageNum(pageQuery::getPage);
        int pageSize = getPageSize(pageQuery::getSize);

        Page<T> page = new Page<>(pageNumber, pageSize);
        if (CollectionUtil.isNotEmpty(pageQuery.getOrders())) {
            page.setOrders(pageQuery.getOrders());
        }
        return page;
    }

    public static <E> PageVO<E> toPage(IPage<E> iPage) {
        return MybatisPageUtil.ofPage(iPage, iPage.getRecords());
    }

    public static <E> PageVO<E> toPage(IPage<?> iPage, List<E> rows) {
        return MybatisPageUtil.ofPage(iPage, rows);
    }

    public static <E> PageVO<E> ofPage(IPage<?> iPage, List<E> rows) {
        PageVO<E> vo = new PageVO<>();
        vo.setTotal(iPage.getTotal());
        vo.setRows(rows);
        vo.setPageNum(iPage.getCurrent());
        vo.setPageSize(iPage.getSize());
        vo.setHasNextPage(iPage.getCurrent() < iPage.getPages());
        return vo;
    }

    public static Integer getPageNum(Supplier<Integer> supplier) {
        Integer pageNum = supplier.get();
        if (pageNum == null) {
            pageNum = PageConstant.DEFAULT_PAGE_NUM;
        }
        return Math.max(pageNum, PageConstant.DEFAULT_PAGE_NUM);
    }

    public static Integer getPageSize(Supplier<Integer> supplier) {
        Integer pageSize = supplier.get();
        if (pageSize == null || pageSize < 1) {
            pageSize = PageConstant.DEFAULT_PAGE_SIZE;
        } else if (pageSize > PageConstant.MAX_PAGE_SIZE) {
            pageSize = PageConstant.MAX_PAGE_SIZE;
        }
        return pageSize;
    }
}
